package com.example.demo.service;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.example.demo.bean.SWarehouse;
import com.example.demo.common.exception.DataValidException;
import com.example.demo.mapper.SEmpMapper;
import com.example.demo.mapper.SInventoryMapper;
import com.example.demo.mapper.SRegionMapper;
import com.example.demo.mapper.SWarehouseMapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

@Service
public class SWarehouseService {

	@Autowired
	private SWarehouseMapper swMapper;
	@Autowired
	private SEmpMapper seMapper;
	@Autowired
	private SRegionMapper srMapper;
	@Autowired
	private SInventoryMapper siMapper;
	
	
	//所有所有仓库信息
	public PageInfo<SWarehouse> findAllByPage(int pageNum, int pageSize){
		PageHelper.startPage(pageNum,pageSize);
		//执行查找行为
		List<SWarehouse> list=swMapper.selectAll();
		if (list==null) {
			list = new ArrayList<>(0);
		}
		return new PageInfo<>(list);
	}
	
	//按条件查找仓库信息
	public PageInfo<SWarehouse> findByCondition(
			Integer id,Integer regionId,Integer managerId,
			int pageNum, int pageSize){
		PageHelper.startPage(pageNum, pageSize);
		List<SWarehouse> list=swMapper.selectByCondition(id, regionId, managerId);
		if (list==null) {
			list = new ArrayList<>(0);
		}
		return new PageInfo<>(list);
	}
	//添加或修改仓库信息
	public void saveOrUpdate(SWarehouse sw) {
		//判断输入的信息中外键是否为空
		if (sw.getRegionId()==null||sw.getManagerId()==null) {
			//判断外键是否完整
			throw new DataValidException("请填写完整信息");
		}
		if (seMapper.selectByPrimaryKey(sw.getManagerId())==null||srMapper.selectByPrimaryKey(sw.getRegionId())==null) {
			throw new DataValidException("外键信息不存在");
		}
		if (sw.getId()==null) {
			swMapper.insert(sw);
		}else {
			swMapper.updateByPrimaryKey(sw);
		}
	}
	//删除仓库信息
	//作为库存信息inventory的外键存在
	public int deleteById(Integer id) {	
		//判断输入的id是否为空
		if (id==null) {
			throw new DataValidException("请输入要删除的id");
		}
		//按id在数据库中查找，找不到报错
		if (swMapper.selectByPrimaryKey(id)==null) {
			throw new DataValidException("删除失败");
		}
		SWarehouse sw=swMapper.selectByPrimaryKey(id);
		if (!siMapper.selectByWareHouse(sw.getId()).isEmpty()) {
			throw new DataValidException("存在下属信息，库存信息，请把下属库存信息删除后，在删除本信息");
		}
		swMapper.deleteByPrimaryKey(id);
		return 0;
	}
	
	//批量删除仓库信息
	public int batchDeleteById(int [] id) {
		//判断输入的id是否为空
		if (id.length==0||id==null) {
			throw new DataValidException("请选择一批要删除的id");
		}
		//在数据库中查看是否存在
		for (int i : id) {
			if (swMapper.selectByPrimaryKey(i)==null) {
				throw new DataValidException("删除失败");
			}
			SWarehouse sw=swMapper.selectByPrimaryKey(i);
			if (!siMapper.selectByWareHouse(sw.getId()).isEmpty()) {
				throw new DataValidException("存在下属信息，库存信息，请把下属库存信息删除后，在删除本信息");
			}
		}
		//删除信息
		swMapper.batchDelete(id);
		return 0;
	}
	
}
